package mapping

import (
	"encoding/json"
	"github.com/golang-module/carbon/v2"
	"simcard/model"
	"simcard/model/entity"
)

// SimCardsEntityToDto entity data transfer
func SimCardsEntityToDto(simCards []*entity.SimCard) []*model.SimCardInfo {
	out := make([]*model.SimCardInfo, 0, len(simCards))
	for _, c := range simCards {
		out = append(out, SimCardEntityToDto(c))
	}
	return out
}

// SimCardEntityToDto entity data transfer
func SimCardEntityToDto(e *entity.SimCard) *model.SimCardInfo {

	var (
		fExpiring = func(s string) bool {
			var (
				now         = carbon.Now(carbon.PRC)
				expiredDate = carbon.ParseByFormat(s, "2006-01-02", carbon.PRC)
			)

			if now.AddDays(7).Gte(expiredDate) && now.Lte(expiredDate) {
				return true
			}
			return false
		}
		fAgentName = func(s json.RawMessage) string {
			var agentDetail = &model.AgentDetail{}
			_ = json.Unmarshal(s, agentDetail)
			return agentDetail.Name
		}
	)
	return &model.SimCardInfo{

		Id: e.Id,

		UserId: e.UserId,

		UserPhone: e.UserPhone,

		AgentId: e.AgentId,
		EbikeId: e.EbikeId,

		AgentName: fAgentName(e.AgentDetail),

		Expiring: fExpiring(e.ExpiredDate),

		Sn: e.Sn,

		FrameCode: e.FrameCode,

		Iccid: e.Iccid,

		EffectiveDate: e.EffectiveDate,

		ExpiredDate: e.ExpiredDate,

		Status: e.Status,

		Detail: e.Detail,

		CreatedAt: e.CreatedAt,

		UpdatedAt: e.UpdatedAt,
	}
}
